package com.cxy521.web;

import com.cxy521.constant.Constants;
import com.cxy521.model.RespMessage;
import com.cxy521.model.bo.MessageBoardBO;
import com.cxy521.repository.MessageBoardDao;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @version 1.0
 * @author： wucheng
 * @date： 2021-08-28 18:33
 */
@Api(value = "留言板管理")
@RestController
@RequestMapping("/message")
@Slf4j
@CrossOrigin(origins = {"http://cxy521.com", "https://cxy521.com"}, maxAge = 3600)
public class MessageBoardController {

    @Autowired
    private MessageBoardDao messageBoardDao;

    @ApiOperation(value = "新增留言", notes = "新增留言接口")
    @PostMapping("/save")
    public RespMessage save(@Validated @RequestBody MessageBoardBO messageBoardBO, HttpServletRequest request) {
        if (messageBoardBO == null || messageBoardBO.getId() !=  null) {
            return RespMessage.error("请输入正确数据");
        }
        String strIP = getRequestIP(request);
        log.info("新增接口，请求ip为：{}, 新增网址为：{}",strIP, messageBoardBO.getWebSite());
        messageBoardBO.setId(null);
        messageBoardBO.setCreatedDate(LocalDateTime.now());
        messageBoardBO.setState(Constants.MessageApproveState.INIT);//默认未审核
        messageBoardDao.save(messageBoardBO);
        return RespMessage.ok();
    }

    @ApiOperation(value = "审批通过", notes = "审批通过当前id的留言信息")
    @PutMapping("/approve/{id}")
    public RespMessage approveMessage(@PathVariable(name = "id") Long id ) {
        if (id == null ) {
            return RespMessage.error("参数异常");
        }
        MessageBoardBO messageBoardBO = messageBoardDao.findById(id).orElse(null);
        if (messageBoardBO == null) {
            return RespMessage.error("参数异常");
        }
        messageBoardBO.setState(Constants.MessageApproveState.PASSED);
        messageBoardDao.save(messageBoardBO);
        return RespMessage.ok().setMsg("审批通过");
    }

    @ApiOperation(value = "忽略当前留言", notes = "忽略当前id的的留言信息")
    @PutMapping("/ignored/{id}")
    public RespMessage ignoredMessage(@PathVariable(name = "id") Long id ) {
        if (id == null ) {
            return RespMessage.error("参数异常");
        }
        MessageBoardBO messageBoardBO = messageBoardDao.findById(id).orElse(null);
        if (messageBoardBO == null) {
            return RespMessage.error("参数异常");
        }
        messageBoardBO.setState(Constants.MessageApproveState.IGNORED);
        messageBoardDao.save(messageBoardBO);
        return RespMessage.ok().setMsg("已忽略");
    }

    @ApiOperation(value = "查询审核后列表", notes = "查询审核后留言列表")
    @GetMapping("/list")
    public RespMessage listMessage() {
        List<MessageBoardBO> list = messageBoardDao.findByState(Integer.parseInt(Constants.MessageApproveState.PASSED.toString()));
        return RespMessage.ok().setObj(list);
    }

    @ApiOperation(value = "查询未审核列表", notes = "查询未审核后留言信息")
    @GetMapping("/listInit")
    public RespMessage listInitMessage() {
        List<MessageBoardBO> list = messageBoardDao.findByState(Integer.parseInt(Constants.MessageApproveState.INIT.toString()));
        return RespMessage.ok().setObj(list);
    }

    @ApiOperation(value = "查询全部信息列表", notes = "查询全部留言信息")
    @GetMapping("/listAll")
    public RespMessage listAllMessage() {
        List<MessageBoardBO> list = messageBoardDao.findAll();
        return RespMessage.ok().setObj(list);
    }

    public static String getRequestIP(HttpServletRequest request) {
        final String UnknownIP = "unknown";
        final String LoopbackIP = "127.0.0.1";

        String strAddr = null;
        try {
            strAddr = request.getHeader("x-forwarded-for");
            if (strAddr == null || strAddr.length() == 0 || UnknownIP.equalsIgnoreCase(strAddr)) {
                strAddr = request.getHeader("Proxy-Client-IP");
            }
            if (strAddr == null || strAddr.length() == 0 || UnknownIP.equalsIgnoreCase(strAddr)) {
                strAddr = request.getHeader("WL-Proxy-Client-IP");
            }
            if (strAddr == null || strAddr.length() == 0 || UnknownIP.equalsIgnoreCase(strAddr)) {
                strAddr = request.getRemoteAddr();
                if (LoopbackIP.equals(strAddr)) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                    }
                    strAddr = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (strAddr != null && strAddr.length() > 15) { // "***.***.***.***".length()
                if (strAddr.indexOf(",") > 0) {
                    strAddr = strAddr.substring(0, strAddr.indexOf(","));
                }
            }
        } catch (Exception e) {
            strAddr = "";
        }

        return strAddr;
    }


}
